package org.itboys.core.service.mongo.front;

import com.alibaba.fastjson.JSONObject;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dto.member.SundayMemberDto;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.util.JNBYRequestUtil;
import org.itboys.core.util.NumberUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2018/10/18
 * 描述：用户信息
 */
@Service
public class SundayFrontMemberService extends BaseMongoService<SundayMember> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Autowired
    private SundayWeixinUserInfoService infoService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayValicodedateService valicodedateService;
    @Autowired
    private SundayFrontGiftService giftService;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    /**
     * 小程序code登录   生成基础用户
     *
     * @param code
     * @return
     * @throws IOException
     */
    public SundayMember loginWithCode(String code) throws IOException {
        String openId = infoService.getOpenId(code);
        return getBySmallOpenId(openId);
    }

    public SundayMemberDto findOne(Long id) {
        SundayMemberDto dto = packageSingleDto(super.getById(id));
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("isDeleted",SundayCommonConstants.NO);
        param.put("receiveId", id);
        param.put("status", SundayCommonConstants.NO);
        if(ListUtil.isNotNull(giftService.list(param))){
            dto.setHasGift(SundayCommonConstants.YES);
        }
        return dto;
    }

    /**
     * 小程序首次登录
     *
     * @param memberId
     * @param code
     * @param encryptedData
     * @param iv
     * @param mobile
     * @param validateCode
     * @return
     * @throws Exception
     */
    public SundayMember loginWithUnion(Long memberId, String code, String encryptedData, String iv, String mobile, String validateCode) throws Exception {
        valicodedateService.checkValidateCode(mobile, validateCode);
        SundayMember member = super.getById(memberId);
        String info = infoService.getUserInfo(code, encryptedData, iv);
        JSONObject userInfoJSON = (JSONObject) JSONObject.parse(info);
        String nickName = String.valueOf(userInfoJSON.get("nickName"));
        String wxLogo = String.valueOf(userInfoJSON.get("avatarUrl"));
        String openId = String.valueOf(userInfoJSON.get("openId"));
        String unionId = String.valueOf(userInfoJSON.get("unionId"));
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", 0);
        //先判断是否存在用户
        param.put("weixinUnionId", unionId);
        List<SundayMember> oldMembers = super.list(param);
        if (ListUtil.isNotNull(oldMembers)) {
            SundayMember oldMember = oldMembers.get(0);
            if (oldMember.getId() != memberId.longValue()) {
                oldMember.setIsLogin(SundayCommonConstants.YES);
                oldMember.setMiniOpenId(openId);
                super.updateExceptEmpty(oldMember.getId(), oldMember);
                //删除新增用户  保留旧用户
                super.delete(memberId);
            }
            return oldMember;
        }
        JSONObject paramJson = new JSONObject();
        paramJson.put("nickName", nickName);
        paramJson.put("imgLogo", wxLogo);
        paramJson.put("unionid", unionId);
        paramJson.put("openid", openId);
        paramJson.put("phone", mobile);
        logger.info("江南布衣创建用户参数"+paramJson.toJSONString());
        JSONObject requestResult = JNBYRequestUtil.request(paramJson, "108d1f62b2e7f5a755230479f5eff13d", SundayCommonConstants.member_add_url);
        logger.info("江南布衣创建用户结果"+requestResult.toJSONString());
        if (!requestResult.get("code").equals("0000")) {
            throw new ErrorException(ExceptionEnum.JNBY_CREATE_USER_EXCEPTION.getValue());
        }
        JSONObject data = (JSONObject) requestResult.get("data");
        String userId = data.getString("userId");
        String cUserId = data.getString("cUserId");
        String cardNo = data.getString("cardNo");
        //保存微信头像
        String random = NumberUtil.generateNumber("JNBY");
        String savePath = resourceHolder.getStringValue("fileUploadPath") + "/logo/" + random + ".jpg";
        ImageUtils.buildImg(savePath, wxLogo);
        //头像半链接
        member.setImage("/logo/" + random + ".jpg");
        member.setWeixinUnionId(unionId);
        member.setIsLogin(SundayCommonConstants.YES);
        member.setNickName(nickName);
        member.setUserId(userId);
        member.setCUserId(cUserId);
        member.setCardNo(cardNo);
        member.setMobile(mobile);
        super.updateExceptEmpty(memberId, member);
        return member;
    }

    /**
     * 处理来至小程序的用户信息。
     *
     * @param openId
     */
    public SundayMember getBySmallOpenId(String openId) {
        SundayMember member = null;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("isDeleted", 0);
        //使用openId标识用户。小程序
        param.put("miniOpenId", openId);
        List<SundayMember> oldMembers = super.list(param);
        if (ListUtil.isNotNull(oldMembers)) {
            member = oldMembers.get(0);
        } else {
            member = new SundayMember();
            member.setMiniOpenId(openId);
            member.setIsLogin(SundayCommonConstants.NO);
            super.save(member);
        }
        return member;
    }

    /**
     * 组装单个
     *
     * @param member
     * @return
     */
    private SundayMemberDto packageSingleDto(SundayMember member) {
        SundayMemberDto dto = new SundayMemberDto();
        BeanUtils.copyProperties(member, dto);
        dto.setImage(resourceHolder.getStringValue("imgRoot")+member.getImage());
        return dto;
    }


}
